/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.util;

import java.util.Iterator;

import mosdi.util.iterators.SegmentationGenerator;

/** Represents a set of bit arrays with a given length and weight (where 
 *  weight means the number of 1-bits). The main purpose of this class
 *  is to provide convenient enumeration of all such bit arrays. */
public class FixedWeightBitArrays implements Iterable<BitArray> {
	private int length;
	private int weight;
	
	public FixedWeightBitArrays(int length, int weight) {
		this.length = length;
		this.weight = weight;
	}

	public Iterator<BitArray> iterator() {
		return new FixedWeightBitArraysIterator();
	}
	
	private class FixedWeightBitArraysIterator implements Iterator<BitArray> {
		Iterator<int[]> positionIterator;

		FixedWeightBitArraysIterator() {
			positionIterator = new SegmentationGenerator(length-weight,weight+1).iterator();
		}
		
		public boolean hasNext() {
			return positionIterator.hasNext();
		}

		public BitArray next() {
			BitArray result = new BitArray(length);
			int[] positions = positionIterator.next();
			int n = 0;
			for (int i=0; i<weight; ++i) {
				n+=positions[i];
				result.set(n, true);
				++n;
			}
			return result;
		}

		public void remove() { throw new UnsupportedOperationException(); }
		
	}
}
